package cn.zzzhy.util;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * @author zzzhy
 * @since 16/2/27 下午7:59
 */
public class HttpClientUtil {

    public static final Integer connTimeout = 10000;
    public static final Integer readTimeout = 10000;
    private static CloseableHttpClient client = HttpClients.createDefault();

    public static String connect(String destUrl, boolean isHttps) {
        if (isHttps) {
            return httpsGet(destUrl);
        }
        return httpGet(destUrl);
    }

    private static String httpsGet(String destUrl) {
        String content = null;
        InputStream inputStream = null;
        CloseableHttpResponse res = null;
        try {
            HttpGet get = new HttpGet(destUrl);

            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            customReqConf.setConnectTimeout(connTimeout);
            customReqConf.setSocketTimeout(readTimeout);
            get.setConfig(customReqConf.build());
            get.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");

            client = getHttpsClient();
            res = client.execute(get);
            HttpEntity entity = res.getEntity();
            inputStream = entity.getContent();
            content = IOUtils.toString(inputStream);
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (res != null) {
                    res.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    private static String httpGet(String destUrl) {
        HttpGet httpGet = new HttpGet(destUrl);
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        String content = null;
        try {
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
            content = IOUtils.toString(inputStream);
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }

    private static CloseableHttpClient getHttpsClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);
        return HttpClients.custom().setSSLSocketFactory(sslFactory).build();
    }

    public static void downloadFile(String webFileUrl, String fileName){
        InputStream in = null;
        OutputStream out = null;
        try{
            // 构造URL
            URL url = new URL(webFileUrl);
            // 打开连接
            System.setProperty("http.agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36");
            URLConnection con = url.openConnection();
            //设置请求超时为5s
            con.setConnectTimeout(5*1000);
            // 输入流
            in = con.getInputStream();

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            out = new FileOutputStream("/Users/zzzhy/yrng/" + fileName + webFileUrl.substring(webFileUrl.lastIndexOf(".")));
            // 开始读取
            while ((len = in.read(bs)) != -1) {
                out.write(bs, 0, len);
            }
        } catch (IOException e) {
            System.out.println("下载文件失败,url:"+webFileUrl+"\r\n");
        } catch (Exception e) {
            System.out.println("下载文件失败,url:"+webFileUrl+"\r\n");
            System.out.println(e.getMessage()+"\r\n"+e.getCause());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ignored) {
                }
            }
        }

    }
}
